package com.ruoyi.project.module.groupProperty.controller;

import com.google.common.collect.HashMultimap;
import com.ruoyi.common.support.Convert;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.module.group.domain.Group;
import com.ruoyi.project.module.group.service.IGroupService;
import com.ruoyi.project.module.groupProperty.service.IGroupPropertyService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.Yaml;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * com.ruoyi.project.module.groupProperty.controller.GroupPropertyImportController
 * <br>
 *
 * @author 蒋カイセキ    Japan-Tokyo  18-12-13 下午4:46<br>
 * ブログ http://www.shoukaiseki.top/<br>
 * E-メール jiang28555@Gmail.com<br>
 **/
@Controller
@RequestMapping("/module/groupPropertyImport")
public class GroupPropertyImportController extends BaseController {

    private String prefix = "module/groupProperty";


    @Resource
    IGroupService groupService;

    @Resource
    IGroupPropertyService groupPropertyService;


    @RequiresPermissions("module:group:add")
    @GetMapping("/importText/{configGroupId}")
    public String configGroupPropertyImport(@PathVariable("configGroupId") Long configGroupId
                                            , ModelMap mmap
    )
    {
        mmap.put("configGroupId", configGroupId);
        return prefix + "/importText";
    }


    @RequiresPermissions("module:group:add")
    @PostMapping("/importText")
    @ResponseBody
    @Transactional
    public AjaxResult configGroupPropertyImport(@RequestParam("configGroupId") Long configGroupId
                                                ,@RequestParam("text") String text
    )
    {
        Group group = groupService.selectGroupById(configGroupId);
        if(group!=null){
            String propertyPrefix = group.getPropertyPrefix();
            Yaml yaml=new Yaml();
            Map hashMap = yaml.loadAs(text, HashMap.class);
            if(propertyPrefix!=null){
                String[] split = (propertyPrefix).split("\\.");
                for (String fieldName:split) {
                    Object o = hashMap.get(fieldName);
                    if(o instanceof Map){
                       hashMap= (Map) o;
                    }
                }
            }
            if(hashMap==null){
                return error(group.getPropertyPrefix()+"属性不存在");
            }

            int i = groupPropertyService.importHierarchicalStructure(hashMap, configGroupId, 0L);
            return toAjax(i);
        }

        return error("configGroupId无有效数据");
    }

}
